# import logging
from flask import current_app, jsonify
from flask import render_template
# from info import redis_store
from flask import request
from flask import session
from info.models import User, Category, News
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/newslist')
def newslist():
    # 获取查询参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "5")
    # current_app.logger.error(cid)
    # current_app.logger.error(page)
    # current_app.logger.error(per_page)
    # 参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = "1"
        per_page = "10"
    # 分页查询，以分类编码分页查询，按创建时间的降序排列
    try:
        # filters = ""
        # if cid != '1':
        #     filters = (News.category_id == cid)
        # paginate = News.query.filter(filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        filters = []
        if cid != '1':
            filters.append(News.category_id == int(cid))
            # print(News.category_id == cid)
            print(filters)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="获取新闻失败")
    # News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).pagenate(page, per_page, False)
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    newsList = []
    for i in items:
        # print(i)
        newsList.append(i.to_dict())
    return jsonify(errno=RET.OK, errmasg="获取新闻成功", totalPage = totalPage, currentPage = currentPage, newsList = newsList)


@index_blue.route('/', methods=['GET','POST'])
def show_index():
    user = None
    user_id = session.get('user_id')
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 热门新闻过滤提交，交互完成
    try:
        hot_news = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="热门新闻获取失败")
    # 组成新闻对象列表，为下一步拼成大列表完成准备工作
    news_list = []
    for i in hot_news:
        # 将新闻中各个属性转化为字典格式。
        news_list.append(i.to_dict())

    # 提取分类信息，列表
    categorys = Category.query.filter().all()
    cate_list = []
    for i in categorys:
        # print(i)
        cate_list.append(i)
    data = {
        'user_info': user.to_dict() if user else "",
        'news_list': news_list,
        'cate_list': cate_list
    }

    return render_template("news/index.html",data=data)


@index_blue.route('/favicon.ico')
def get_web_logo():
    return current_app.send_static_file('news/favicon.ico')